﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;


/// <summary>
/// Summary description for parents
/// </summary>
/// 

namespace Bestlife.ERP.DataAccess
{
    
    public class parents :System.Web.UI.Page
    {
        String updusersID;
        Double  updbv;
        Double updTotalCommitions;
        String Get_parentID;
        Double getusercpv;
        Double store_cpv;
        String parentstaus;
        SqlDataReader rdRptatus;
        SqlDataReader rdR;
        SqlDataReader rdRccpv;
        Double strore_parent_ppv;

        public static String userID;// Current user id 
        public static String parentID;//Get parent id 
        public static String parentStatus; //Get parent Details 
        List<string> Uper_Parent = new List<string>();
        String returnID;
        Boolean chkpm;



        #region update parents details

        public Boolean UpdateParent(String id, double bv, double TotalCommitions, double product_pv, String child_status, double indecomm)
        {

            updusersID=id;
            updbv=bv;
            updTotalCommitions=TotalCommitions;

            string parent_status = ParentDetails(id);
            try
            {
                Get_parentID = parent(updusersID); // get parent id from  parent method
            }


            catch (Exception err)
            {

                Response.Redirect("404.aspx?Massage=" + err.Message.ToString() + "Get Parent ID");
            }

           // DataAccess.parentCPV ppcv = new parentCPV();
           // store_cpv = ppcv.calculate_ParentCPV(updusersID);// get parent cpv

           // store_cpv = 5.00;

            Double calculated_cpv = product_pv;
            
            Boolean upd = false;
            try
            {
               DataAccess.parentCPV Pcpv = new parentCPV();// Get parent CPV
               Double getcpv=Pcpv.calculate_ParentCPV(Get_parentID);
               Double month_cpv = Pcpv.calculate_Parentmont_CPV(Get_parentID);
             
               Double Tot_monthCPV = month_cpv + calculated_cpv;
               Double Total_cpv = getcpv + calculated_cpv; 


               DataAccess.parentCPV pbv = new parentCPV();// Get parent bv
               Double parents_bv=pbv.calculate_Parentbv(Get_parentID);

               Double totalbv = bv + parents_bv;

               String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
               Bestlife.ERP.DataAccess.clsCon.connect(connStr);

               DataAccess.parentCPV prntpv = new parentCPV(); //////////// GET PARENT PV  (???????)
               strore_parent_ppv = prntpv.calculate_Parentppv(Get_parentID);

               DataAccess.parentCPV ptbv = new parentCPV();
               Double Parent_TBV = ptbv.calculate_Parentotal_bv(Get_parentID);

               Double Calculate_Parent_TotalBV =Math.Round(Parent_TBV + bv,2);



                // GET TPV
               Bestlife.ERP.DataAccess.D_bonus bns = new DataAccess.D_bonus();//(Add by chathuranga)
               Bestlife.ERP.Entities.E_Bonus ebns2 = new Entities.E_Bonus();//(Add by chathuranga)
               ebns2 = bns.Getbonus(Get_parentID);
               Double tppv_month = double.Parse(ebns2.Tppv_month.ToString()) + product_pv;
               Double tbv_month = double.Parse(ebns2.Tbv_month.ToString())+bv;
               Double Store_tpv = double.Parse(ebns2.Tpv.ToString()) + product_pv;

               //check 1-5 status 
               if (parent_status.Equals("1") || parent_status.Equals("2") || parent_status.Equals("3") || parent_status.Equals("4") || parent_status.Equals("5") || parent_status.Equals("5.1") || parent_status.Equals("6") || parent_status.Equals("7") || parent_status.Equals("8") || parent_status.Equals("9") || parent_status.Equals("10"))
               {
               
                          BusinessRules.Check_montlyPV mparent = new BusinessRules.Check_montlyPV();
                          Boolean chkpm = mparent.check_monthlyPV(Get_parentID, parent_status);   
                   
                   if (chkpm==true)
                      {
                                               
                          connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                          Bestlife.ERP.DataAccess.clsCon.connect(connStr);
                          String act = "UPDATE Bonus  SET Cpv='" + Total_cpv + "',CPV_month='" + Tot_monthCPV + "',tppv_month='" + tppv_month + "',tbv_month='" + tppv_month + "',Tbv='" + Calculate_Parent_TotalBV + "', T_commision='" + TotalCommitions + "',Last_Modify='" + System.DateTime.Now + "'  WHERE User_id='" + Get_parentID + "'";
                          Bestlife.ERP.DataAccess.clsCon.AddEditDel(act);
                      }
                        else 
                      {
                          Bestlife.ERP.DataAccess.D_bonus bnsch = new DataAccess.D_bonus();//(Add by chathuranga)
                          Bestlife.ERP.Entities.E_Bonus ebnsch = new Entities.E_Bonus();//(Add by chathuranga)
                          double DbStorebv= double.Parse(ebns2.Storebv.ToString());
                          double DbStorepv = double.Parse(ebns2.Storepv.ToString());
                       
                          double totstbv = totalbv + DbStorebv;
                          double totstpv = Store_tpv + DbStorepv;
                          Bestlife.ERP.BusinessRules.update_Status ups = new BusinessRules.update_Status();
                          double commi=Math.Round(ups.storeComm(Get_parentID, indecomm),4);
                          ebnsch = bnsch.Getbonus(Get_parentID);
                       
                          double tppv_monthch = double.Parse(ebnsch.Tppv_month.ToString()) + product_pv;
                          double tbv_monthch = double.Parse(ebnsch.Tbv_month.ToString()) + bv;

                          connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                          Bestlife.ERP.DataAccess.clsCon.connect(connStr);
                          String act = "UPDATE Bonus  SET Cpv='" + Total_cpv + "',CPV_month='" + Tot_monthCPV + "',tppv_month='" + tppv_monthch + "',tbv_month='" + tbv_monthch + "', Tbv='" + Calculate_Parent_TotalBV + "', Store_comm='" + commi  + "',Last_Modify='" + System.DateTime.Now + "'  WHERE User_id='" + Get_parentID + "'";
                          Bestlife.ERP.DataAccess.clsCon.AddEditDel(act);

                      }

               }



                
            }

            catch (Exception err)
            {

                Response.Redirect("404.aspx?Massage=" + err.Message.ToString());
            }

            finally
            {
                clsCon.conn_new.Close();
                
            }

            return upd;
        }

        #endregion


        # region Get Parent Details- parent ID
        public String parent (String id)
              {

                  try
                  { //try
                      String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                      Bestlife.ERP.DataAccess.clsCon.connect(connStr);

                      String Ssql = "SELECT d.Sup_ID,b.user_Status from Tbl_Distributor d, Bonus b where d.Dis_ID='" + id + "' AND d.Sup_ID=b.User_id";
                      //SqlDataReader ldr = Bestlife.ERP.DataAccess.clsCon.ReadTable(Ssql);

                      
                      rdR = clsCon.ReadTable(Ssql);


                      if (rdR.Read())
                      {
                          parentStatus = rdR["user_Status"].ToString();
                          returnID = rdR["Sup_ID"].ToString();
                      }

                  } //try

                  catch (Exception err)
                  {

                      Response.Redirect("404.aspx?Massage=" + err.Message.ToString());
                  }

                    
                  finally
                   
                  {
                     clsCon.conn_new.Close();
                     rdR.Close();

                  }   //finally

                  return returnID;

              }//close method

        #endregion

       
        # region Get Parent Status

        public String ParentDetails(String id)
        {

            try
            {//try

                String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                Bestlife.ERP.DataAccess.clsCon.connect(connStr);

                String sqlptatus = "SELECT d.Sup_ID,b.user_Status from Tbl_Distributor d, Bonus b where d.Dis_ID='"+id+"' AND d.Sup_ID=b.User_id";
                rdRptatus = clsCon.ReadTable(sqlptatus);


                if (rdRptatus.Read())
                {
                    parentstaus = rdRptatus["user_Status"].ToString();
                    
                    
                }




            }//try


            catch (Exception err)
            {

                Response.Redirect("404.aspx?Massage=" + err.Message.ToString());
            }

            finally
            {
                clsCon.conn_new.Close();
                rdRptatus.Close();


            }   //finally
            return parentstaus;
        }

        #endregion


        #region update Leadership commition

        public Boolean UpdateLcommition(String id, Double L_ship, Double Productpv,Double Productbv)// add lship by chathuranga 
        {
            
           Boolean upd = false;


           Bestlife.ERP.DataAccess.D_bonus bns = new DataAccess.D_bonus();//(Add by chathuranga)
           Bestlife.ERP.Entities.E_Bonus ebns1 = new Entities.E_Bonus();//(Add by chathuranga)
           ebns1 = bns.Getbonus(id);
            try
            {

                Double totalProductPV=double.Parse(ebns1.Tpv.ToString())+Productpv;
                Double totalProductBV = double.Parse(ebns1.Bv.ToString()) + Productbv;
                Double totalProductCPV = double.Parse(ebns1.Cpv.ToString())+Productpv;
                Double totalProductTBV = double.Parse(ebns1.Tbv.ToString()) + Productbv;

                //for store bv n pv
                Double totalProductSPV = double.Parse(ebns1.Storepv.ToString()) + Productpv;
                Double totalProductSBV = double.Parse(ebns1.Storebv.ToString()) + Productbv;

                BusinessRules.Check_montlyPV mparent = new BusinessRules.Check_montlyPV();
                Boolean chkpm = mparent.check_monthlyPV(id, ebns1.User_Status);
                Boolean check_month_Lpv = mparent.check_monthlyLshipPV(id, ebns1.User_Status);
                if (chkpm && check_month_Lpv)
                {
                    Double TotL_ship = double.Parse(ebns1.T_Lship.ToString()) + L_ship;
                    String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                    Bestlife.ERP.DataAccess.clsCon.connect(connStr);
                    String updtxt = "UPDATE Bonus  SET  T_Lship='" + TotL_ship + "',Last_Modify='" + System.DateTime.Now + "' WHERE User_id='" + id + "' ";
                    upd = Bestlife.ERP.DataAccess.clsCon.AddEditDel(updtxt);
                }
                else 
                {
                    Double TotL_ship_store = double.Parse(ebns1.Store_Lship.ToString()) + L_ship;
                    String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                    Bestlife.ERP.DataAccess.clsCon.connect(connStr);
                    String updtxt = "UPDATE Bonus  SET  Store_Lship='" + TotL_ship_store + "',Last_Modify='" + System.DateTime.Now + "' WHERE User_id='" + id + "' ";
                    upd = Bestlife.ERP.DataAccess.clsCon.AddEditDel(updtxt);
                }
            }

            catch (Exception err)
            {

                Response.Redirect("404.aspx?Massage=" + err.Message.ToString());
            }

            finally
            {
                clsCon.conn_new.Close();

            }

            return upd;
        }

        #endregion


        # region Get All Parent

        public string parentAllRunner(String id,string st) 
        {
       
        double firstchild_st=double.Parse(st);   
        Bestlife.ERP.Entities.E_Bonus E_chlist = new Bestlife.ERP.Entities.E_Bonus();
        Bestlife.ERP.DataAccess.D_bonus getData = new Bestlife.ERP.DataAccess.D_bonus();
            List<string> returnList = new List<string>();
            returnList.Clear();
            string returnBest = "";
            Uper_Parent.Clear();
            returnList = parentAll(id);
             
            foreach (string Rlist in returnList) 
            {
                E_chlist=getData.Getbonus(Rlist);
                double userst = double.Parse(E_chlist.User_Status);
                if (firstchild_st <= userst || (firstchild_st == 5.1 && userst == 5) || (firstchild_st == 5.1 && userst == 5))
                    {
                        if ((userst <= 6 && (E_chlist.Ppv >= 25)) || (userst == 7 && (E_chlist.Ppv >= 50)) || (userst == 8 && (E_chlist.Ppv >= 75)) || (userst == 9 && (E_chlist.Ppv >= 100)) || (userst == 10 && (E_chlist.Ppv >= 200))) //if Person Who dosent Reach his monthly process availability
                        {
                            returnList.Clear();
                            returnBest = Rlist;
                            return returnBest;
                        }
                    }
            }

            return returnBest;
        }
        public List<string> parentAll(String id)
        {
            
            string supID = "";
            try
            { //try
                String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                Bestlife.ERP.DataAccess.clsCon.connect(connStr);

                String Ssql = "SELECT d.Sup_ID,b.user_Status from Tbl_Distributor d, Bonus b where d.Dis_ID='" + id + "' AND d.Sup_ID=b.User_id";
                //SqlDataReader ldr = Bestlife.ERP.DataAccess.clsCon.ReadTable(Ssql);


                rdR = clsCon.ReadTable(Ssql);


                if (rdR.Read())
                {
                   
                    supID = rdR["Sup_ID"].ToString();
                    Uper_Parent.Add(supID);
                }
                rdR.Close();


                if (supID.Equals(""))
                {
                    return Uper_Parent;
                    
                }
                else { parentAll(supID); }

            } //try

            catch (Exception err)
            {

                Response.Redirect("404.aspx?Massage=" + err.Message.ToString());
            }


            finally
            {
                clsCon.conn_new.Close();
               

            }   //finally

            return Uper_Parent;

        }//close method

        #endregion









        public Boolean UpdateParenttpvmonth(String id, double bv,double product_pv, String child_status)
        {

         
            //updusersID = id;
            updbv = bv;
            Get_parentID = id;

            string parent_status = ParentDetails(id);
            //try
            //{
            //    Get_parentID = parent(updusersID); // get parent id from  parent method
            //}


            //catch (Exception err)
            //{

            //    Response.Redirect("404.aspx?Massage=" + err.Message.ToString() + "Get Parent ID");
            //}

            // DataAccess.parentCPV ppcv = new parentCPV();
            // store_cpv = ppcv.calculate_ParentCPV(updusersID);// get parent cpv

            // store_cpv = 5.00;

            Double calculated_cpv = product_pv;

            Boolean upd = false;
            try
            {
                DataAccess.parentCPV Pcpv = new parentCPV();// Get parent CPV
                Double getcpv = Pcpv.calculate_ParentCPV(Get_parentID);
                Double month_cpv = Pcpv.calculate_Parentmont_CPV(Get_parentID);

                Double Tot_monthCPV = month_cpv + calculated_cpv;
                Double Total_cpv = getcpv + calculated_cpv;


                DataAccess.parentCPV pbv = new parentCPV();// Get parent bv
                Double parents_bv = pbv.calculate_Parentbv(Get_parentID);

                Double totalbv = bv + parents_bv;

                String connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                Bestlife.ERP.DataAccess.clsCon.connect(connStr);

                DataAccess.parentCPV prntpv = new parentCPV(); //////////// GET PARENT PV  (???????)
                strore_parent_ppv = prntpv.calculate_Parentppv(Get_parentID);

                DataAccess.parentCPV ptbv = new parentCPV();
                Double Parent_TBV = ptbv.calculate_Parentotal_bv(Get_parentID);
                Double Calculate_Parent_TotalBV = Parent_TBV + bv;


                // GET TPV
                Bestlife.ERP.DataAccess.D_bonus bns = new DataAccess.D_bonus();//(Add by chathuranga)
                Bestlife.ERP.Entities.E_Bonus ebns2 = new Entities.E_Bonus();//(Add by chathuranga)
                ebns2 = bns.Getbonus(Get_parentID);
                Double tppv_month = double.Parse(ebns2.Tppv_month.ToString()) + product_pv;
                Double tbv_month = double.Parse(ebns2.Tbv_month.ToString()) + bv;
                Double Store_tpv = double.Parse(ebns2.Tpv.ToString()) + product_pv;

                //check 1-5 status 
                if (parent_status.Equals("1") || parent_status.Equals("2") || parent_status.Equals("3") || parent_status.Equals("4") || parent_status.Equals("5") || parent_status.Equals("5.1") || parent_status.Equals("6") || parent_status.Equals("7") || parent_status.Equals("8") || parent_status.Equals("9") || parent_status.Equals("10"))
                {

                    BusinessRules.Check_montlyPV mparent = new BusinessRules.Check_montlyPV();
                   // Boolean chkpm = mparent.check_monthlyPV(Get_parentID, parent_status);

                    //if (chkpm == true)
                    {

                        connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
                        Bestlife.ERP.DataAccess.clsCon.connect(connStr);
                        String act = "UPDATE Bonus  SET Cpv='" + Total_cpv + "',CPV_month='" + Tot_monthCPV + "',tppv_month='" + tppv_month + "',tbv_month='" + tbv_month + "',Tbv='" + Calculate_Parent_TotalBV + "',Last_Modify='" + System.DateTime.Now + "'  WHERE User_id='" + Get_parentID + "'";
                       Boolean r= Bestlife.ERP.DataAccess.clsCon.AddEditDel(act);
                       if (r)
                       {
                       }
                       else
                       {
                       }
                    }
                  

                }


            }

            catch (Exception err)
            {

                Response.Redirect("404.aspx?Massage=" + err.Message.ToString());
            }

            finally
            {
                clsCon.conn_new.Close();

            }

            return upd;
        }

       




    }/// close public parents


   


} // close Namespase
